<?

class myTwitter {
	
	protected $page_id = NULL;
	protected $months = 4;
	
	function __construct(){
	
	}	
	
	function set_page_id($page_id){
		$this->page_id = $page_id;
	}

	function set_months($months){
		$this->months = $months;
	}

	
	function get_tweets(){
		global $db;
		
		$monat = mktime(0,0,0, date('m'), 1, date('Y') );
		$monat_ab = mktime(0,0,0, date('m', time() - 86400*28*$this->months), 1, date('Y') );

		unset($this->all_tweets);
		
		for($i = 1; $i <= 20; $i++){
	
			$url  = "https://api.twitter.com/1/statuses/user_timeline.json?";
			$url .= "include_entities=true&include_rts=true&screen_name=" . $this->page_id . "&count=200&trim_user=0&exclude_replies=0&page=" . $i;
									
			$json = $db->get_data('twitter', $url);
																		
			if($json == false){

				// sendRequest
				// note how referer is set manually
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_REFERER, 'http://www.' . uniqid('a') .'.net/');
				$body = curl_exec($ch);
				curl_close($ch);
				
				if(eregi('Rate limit exceeded', $body) )
					$twitter_limit = true;
								
				// now, process the JSON string
				$json = json_decode($body, true);
				if(is_array($json) && !$twitter_limit){			
					foreach($json as $row)
						$json_new[] = array(
							'created_at' => $row['created_at'],
							'retweet_count' => $row['retweet_count'],
							'in_reply_to_status_id' => $row['in_reply_to_status_id'],
							);
				$db->save_data('twitter', $url, $json_new);		
				$json = $json_new;
				}
				else{
					mail('sb@sb-web.net', 'twitter_error ' . $url, $body);
					break;
				}
			}
			
						
			if(is_array($json) )			
				foreach($json as $row){
								
					$date = date_parse($row['created_at']);
					
					$tstamp = mktime($date['hour'], $date['minute'], $date['second'], $date['month'], $date['day'], $date['year']);
					
					if($tstamp <= $monat_ab){
						$i = 1000;
						break;
					}
					
					$reply = 0;
					$post = 1;
					if($row['in_reply_to_status_id'] != ''){
						$reply = 1;
						$post = 0;
					}
									
					$this->all_tweets[] = array(
						'tstamp' => $tstamp,
						'tweet_count' => $post,
						'retweet_count' => $row['retweet_count'],
						'reply_count' => $reply,
						);
				}
		}
	
	if($twitter_limit)
		return false;
	
	return $this->all_tweets;	
	}
		
}

?>